<template>
  <div class="wrapper">
    <div id="Address">
      <slot name="header">
        <header v-if="showFilter">
          <el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
        </header>
      </slot>

      <section>
        <el-tree
          :data="treeData"
          :props="treeProps"
          :node-key="nodeKey"
          :filter-node-method="filterNode"
          ref="$treeRef"
          :show-checkbox="showCheckBox"
        >
        </el-tree>
      </section>
      <slot name="footer">
        <div style="display: flex">
          <el-button type="danger" @click="resetHandle"> 重置 </el-button>
          <el-button type="primary" @click="submitHandle"> 确认 </el-button>
        </div>
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

const $emit = defineEmits(['onConfirm'])
const $props = defineProps({
  treeData: {
    type: Array,
    default: () => []
  },
  treeProps: {
    type: Object,
    default: () => ({
      children: 'children',
      label: 'label'
    })
  },
  nodeKey: {
    type: String,
    default: 'id'
  },
  showCheckBox: {
    type: Boolean,
    default: true
  },
  showFilter: {
    type: Boolean,
    default: true
  }
})

const filterText = ref('')
const $treeRef = ref()

watch(filterText, (val: any) => {
  $treeRef.value.filter(val)
})

const filterNode = (value: any, data: any) => {
  if (!value) return true
  return data[$props.treeProps.label].indexOf(value) !== -1
}
const submitHandle = () => {
  let nodes = $treeRef.value.getCheckedNodes()
  nodes = nodes.map((x: any) => {
    let v = $treeRef.value.getNode(x[$props.nodeKey])
    return {
      ...x,
      parent: v.parent
    }
  })
  let dealNodes = nodes.filter((x: any) =>
    x.parent.level === 0 ? x : x.parent.childNodes.some((y: any) => !y.checked)
  )
  $emit('onConfirm', dealNodes)
  console.log('---dwd-area-selector---', dealNodes)
}
const resetHandle = () => {
  $treeRef.value.setCheckedNodes([])
  $emit('onConfirm', [])
}
</script>

<style lang="less" scoped>
#Address {
  width: 100%;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
  section {
    flex: 1;
    overflow: auto;
  }
}
</style>
